package it.ricettario;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;

import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class RicettarioViewerDemo{

	private static final String RICETTE_DIR = "./Ricette";

	private JFrame frame;

	private DefaultMutableTreeNode rootNode;
	private DefaultTreeModel treeModel;
	private JTree tree;
	private JComponent imageContentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					RicettarioViewerDemo window = new RicettarioViewerDemo();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public RicettarioViewerDemo() throws Exception {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() throws Exception {
		frame = new JFrame();
		frame.setTitle("Ricettario");
		frame.getContentPane().setLayout(new BorderLayout(0, 0));

		JToolBar toolBar = new JToolBar();
		frame.getContentPane().add(toolBar, BorderLayout.NORTH);
		frame.setBounds(100, 100, 646, 472);
		
		Component horizontalStrut = Box.createHorizontalStrut(60);
		toolBar.add(horizontalStrut);

		JButton btnCarica = new JButton("Carica ricette");
		btnCarica.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				clear();
				loadTree();
				frame.getContentPane().add(tree, BorderLayout.CENTER);
			}
		});
		btnCarica.setToolTipText("Effettua la scansione delle ricette");
		toolBar.add(btnCarica);

		Component horizontalStrut1 = Box.createHorizontalStrut(57);
		toolBar.add(horizontalStrut1);

		JButton btnEsci = new JButton("Esci");
		btnEsci.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				frame.dispose();
			}
		});
		btnEsci.setToolTipText("Chiude l'applicazione");
		toolBar.add(btnEsci);

		rootNode = new DefaultMutableTreeNode("Ricette");
		treeModel = new DefaultTreeModel(rootNode);
		loadTree();

		
//		String imagePath = "C:\\Progetti\\Ricettario\\workspace\\Ricettario\\Ricette\\1 - ANTIPASTI\\focaccette con olive.jpg";
//
//		final JScrollPane scrollPane = new JScrollPane();
//		 ImageIcon david = createImageIcon(imagePath);
//		ScrollablePicture picture = new ScrollablePicture(david, 10);
//		//scrollPane.setViewportBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
//		scrollPane.setBackground(Color.GREEN);
//		JPanel panelImage = new ShowImage(imagePath, 500,  500);
//		scrollPane.createHorizontalScrollBar();
//		scrollPane.createVerticalScrollBar();
//		scrollPane.setVisible(true);
//		scrollPane.setViewportView(panelImage);
//		//scrollPane.add(panelImage);
//		scrollPane.setWheelScrollingEnabled(true);
//		scrollPane.setAutoscrolls(true);
//		scrollPane.repaint();
        imageContentPane = new ScrollDemo(null);
        imageContentPane.setOpaque(true); //content panes must be opaque
        JPanel panelImage = new JPanel(false);
        panelImage.getToolkit().getImage("C:\\Progetti\\Ricettario\\workspace\\Ricettario\\Ricette\\1 - ANTIPASTI\\focaccette con olive.jpg");
//        VolatileImage volatileImage = panelImage.createVolatileImage(200, 200);
//        volatileImage.createGraphics().drawImage(new ImageIcon(ReadImage()).getImage(), 0, 0, null);
		frame.getContentPane().add(panelImage, BorderLayout.CENTER);
		
		final JPanel panel = new JPanel();
		frame.getContentPane().add(panel, BorderLayout.WEST);
		tree = new JTree(treeModel);
		panel.add(tree);
		tree.setEditable(false);
		tree.setAutoscrolls(true);

		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		tree.setShowsRootHandles(true);
		 MouseListener ml = new MouseAdapter() {
		     public void mousePressed(MouseEvent e) {
		         int selRow = tree.getRowForLocation(e.getX(), e.getY());
		         TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
		         if(selRow != -1) {
		             if(e.getClickCount() == 1) {
		            	 Object[] paths = selPath.getPath();
		            	 File file =((NodeBean)((javax.swing.tree.DefaultMutableTreeNode)paths[paths.length-1]).getUserObject()).getFile();
		            	 
		            	 frame.remove(imageContentPane);
		            	 //frame.repaint();
		            	 ((ScrollDemo)imageContentPane).setPicture(null);
		            	 
		            	 imageContentPane = null;
		            	 System.gc();
		            	 imageContentPane = new ScrollDemo(file.getPath());
		                 imageContentPane.setOpaque(true); //content panes must be opaque
		                 frame.getContentPane().add(imageContentPane, BorderLayout.CENTER);
		                 
		                 //frame.repaint();

		            	 System.out.println(file.getPath());
		             }
		             else if(e.getClickCount() == 2) {
		            	 Object[] paths = selPath.getPath();
		            	 File file =((NodeBean)((javax.swing.tree.DefaultMutableTreeNode)paths[paths.length-1]).getUserObject()).getFile();
						 System.out.println(file.getPath());
						 ((ScrollDemo)imageContentPane).getGraphics().dispose();
						 ((ScrollDemo)imageContentPane).clear();
		            	 System.gc();
		            	 imageContentPane = new ScrollDemo(file.getPath());
		                 imageContentPane.setOpaque(true); //content panes must be opaque
		                 //imageContentPane.revalidate();
		                 //imageContentPane.repaint();
		                 //frame.pack();
		                 frame.getContentPane().add(imageContentPane, BorderLayout.CENTER);						 
						 //frame.repaint();
		             }
		         }
		     }
		 };
		 tree.addMouseListener(ml);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}

	/** Remove all nodes except the root node. */
	public void clear() {
		rootNode.removeAllChildren();
		treeModel.reload();
	}

	public void loadTree() {
		createNodes(new File(RICETTE_DIR), this.rootNode);
	}

	private void createNodes(File fileIn, DefaultMutableTreeNode top) {
		DefaultMutableTreeNode category = null;
		DefaultMutableTreeNode book = null;

		if (!fileIn.exists())
			return;
		FilenameFilter filenameFilter = new FilenameFilter() {
			
			public boolean accept(File dir, String name) {
				//filesHasMap.put(dir + name,dir + "\\" + name);
				if (name.endsWith(".db"))
					return false;
				return true;
			}
		};
		File[] files = dirListByAscendingName(fileIn, filenameFilter);
		
		for (int i = 0; i < files.length; i++) {
			// System.out.println(files[i]);
			if (files[i].isDirectory()) {
				System.out.println("DIR = " + files[i].getName());
				category = new DefaultMutableTreeNode(new NodeBean(files[i], files[i].getName()));
				top.add(category);
				createNodes(files[i], category);
			} else if (files[i].isFile()) {
				book = new DefaultMutableTreeNode(new NodeBean(files[i], files[i].getName()));
				top.add(book);
				System.out.println("Ricetta = " + files[i].getName());
			}
		}

	}

	@SuppressWarnings("unchecked")
	public static File[] dirListByAscendingName(File folder, FilenameFilter filenameFilter) {
		if (!folder.isDirectory()) {
			return null;
		}
		File files[] = folder.listFiles(filenameFilter);
		Arrays.sort(files, new Comparator() {
			public int compare(final Object o1, final Object o2) 
			{
				return new String(((File) o1).getName()).compareTo(new String(((File) o2).getName()));
			}
		});
		return files;
	}
	
    public BufferedImage ReadImage(){
        BufferedImage bi = null;
        int width;
        int height;
        
        try {
             InputStream in = new FileInputStream("C:\\Progetti\\Ricettario\\workspace\\Ricettario\\Ricette\\1 - ANTIPASTI\\focaccette con olive.jpg");
             bi = ImageIO.read(in);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(0);
        }
        
        height = bi.getHeight();
        width = bi.getWidth();
        return bi;
    }	
     
}
